package nc.bs.dao;

import java.lang.reflect.Array;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import nc.bs.logging.Logger;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.IVOPersistence;
import nc.jdbc.framework.DataSourceCenter;
import nc.jdbc.framework.JdbcSession;
import nc.jdbc.framework.PersistenceManager;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.exception.DbException;
import nc.jdbc.framework.exception.ExceptionFactory;
import nc.jdbc.framework.exception.UnKnownException;
import nc.jdbc.framework.mapping.IMappingMeta;
import nc.jdbc.framework.mapping.MappingMeta;
import nc.jdbc.framework.processor.BeanMappingListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.ResultSetProcessor;
import nc.jdbc.framework.util.DBUtil;
import nc.vo.pub.SqlSupportVO;
import nc.vo.pub.SuperVO;
import nc.vo.pub.UpdateResultVO;
import uap.sec.esapi.UAPESAPI;









public final class BaseDAO
  implements IVOPersistence, IUAPQueryBS
{
  private String dataSource = null;
  
  int maxRows = -1;
  
  boolean addTimestamp = true;
  boolean sqlTranslate = true;
  
  public BaseDAO() {}
  
  private static Map<String, ColCache> colCacheMap = new ConcurrentHashMap();
  
  static class ColCache {
    private Map<String, List<String>> nameCache = new ConcurrentHashMap();
  }













  
  public BaseDAO(String dataSource) { this.dataSource = dataSource; }



  
  private String ds() { return (this.dataSource == null) ? DataSourceCenter.getInstance().getSourceName() : this.dataSource; }
  
  private ColCache getColCache() {
    String ds = ds();
    synchronized (colCacheMap) {
      ColCache colCache = (ColCache)colCacheMap.get(ds);
      if (colCache == null) {
        colCache = new ColCache();
        colCacheMap.put(ds, colCache);
      } 
      return colCache;
    } 
  }





  
  public Object executeQuery(String sql, ResultSetProcessor processor) throws DAOException {
    PersistenceManager manager = null;
    Object value = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      JdbcSession session = manager.getJdbcSession();
      session.setSQLTranslator(this.sqlTranslate);
      value = session.executeQuery(sql, processor);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return value;
  }







  
  public Object executeQuery(String sql, SQLParameter parameter, ResultSetProcessor processor) throws DAOException {
	  PersistenceManager manager = null;
    Object value = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      JdbcSession session = manager.getJdbcSession();
      session.setSQLTranslator(this.sqlTranslate);
      value = session.executeQuery(sql, parameter, processor);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return value;
  }







  
  public int executeUpdate(String sql, SQLParameter parameter) throws DAOException {
    int value;
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      JdbcSession session = manager.getJdbcSession();
      session.setSQLTranslator(this.sqlTranslate);
      value = session.executeUpdate(sql, parameter);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return value;
  }






  
  public int executeUpdate(String sql) throws DAOException {
    int value;
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      JdbcSession session = manager.getJdbcSession();
      session.setSQLTranslator(this.sqlTranslate);
      value = session.executeUpdate(sql);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return value;
  }








  
  public Collection retrieveAll(Class className) throws DAOException {
	  PersistenceManager manager = null;
    Collection values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      values = manager.retrieveAll(className);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return values;
  }








  
  public Collection retrieveByClause(Class className, String condition) throws DAOException {
	  PersistenceManager manager = null;
    Collection values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      values = manager.retrieveByClause(className, condition);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return values;
  }

  
  public Collection retrieveByClause(Class className, String condition, SQLParameter params) throws DAOException { return retrieveByClause(className, condition, (String[])null, params); }











  
  public Collection retrieveByClause(Class className, String condition, String orderBy) throws DAOException { return retrieveByClause(className, appendOrderBy(condition, orderBy), (String[])null, null); }



  
  public Collection retrieveByClause(Class className, String condition, String orderBy, SQLParameter params) throws DAOException { return retrieveByClause(className, appendOrderBy(condition, orderBy), (String[])null, params); }










  
  public Collection retrieveByClause(Class className, String condition, String[] fields) throws DAOException { return retrieveByClause(className, condition, fields, null); }


  
  public Collection retrieveByClause(Class className, String condition, String[] fields, SQLParameter params) throws DAOException {
    PersistenceManager manager = null;
    Collection values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      values = manager.retrieveByClause(className, condition, fields, params);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return values;
  }













  
  public Collection retrieveByClause(Class className, String condition, String orderBy, String[] fields) throws DAOException { return retrieveByClause(className, appendOrderBy(condition, orderBy), fields); }



  
  public Collection retrieveByClause(Class className, String condition, String orderBy, String[] fields, SQLParameter params) throws DAOException { return retrieveByClause(className, appendOrderBy(condition, orderBy), fields, params); }

  
  private String appendOrderBy(String condition, String orderBy) {
    StringBuffer clause = new StringBuffer();
    if (condition != null) {
      clause.append(condition);
    }
    if (orderBy != null && condition == null) {
      clause.append("ORDER BY ").append(orderBy);
    }
    if (orderBy != null && condition != null) {
      clause.append(" ORDER BY ").append(orderBy);
    }
    
    return clause.toString();
  }










  
  public Object[] retrieveByClause(Class c, SqlSupportVO[] sqlvos, String fromStr, String strWhere, String strOrderBy) throws DAOException {
    if (sqlvos == null || sqlvos.length == 0) {
      throw new NullPointerException("Sqlvos is null;");
    }
    if (fromStr == null) {
      throw new NullPointerException("fromStr is null;");
    }
    String[][] fields = new String[2][sqlvos.length];
    MappingMeta meta = new MappingMeta("", "");
    for (int i = 0; i < sqlvos.length; i++) {
      fields[0][i] = sqlvos[i].getSqlSelectField();
      fields[1][i] = sqlvos[i].getVoAttributeName();
      meta.addMapping(sqlvos[i].getVoAttributeName(), sqlvos[i].getSqlSelectField());
    } 
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      JdbcSession session = manager.getJdbcSession();
      StringBuffer sql = new StringBuffer("SELECT ");
      for (int i = 0; i < fields[0].length; i++) {
        sql.append(fields[0][i]);
        if (i != fields[0].length - 1) {
          sql.append(",");
        }
      } 
      sql.append(" FROM ").append(fromStr);

      
      if (strWhere != null && strWhere.trim().length() != 0) {
        sql.append(" WHERE ").append(strWhere);
      }
      
      if (strOrderBy != null && strOrderBy.trim().length() != 0) {
        sql.append(" ORDER BY ").append(strOrderBy);
      }
      BeanMappingListProcessor beanMappingListProcessor = new BeanMappingListProcessor(c, meta);
      List result = (List)session.executeQuery(sql.toString(), beanMappingListProcessor);
      return result.toArray((Object[])Array.newInstance(c, 0));
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      
      if (manager != null) {
        manager.release();
      }
    } 
  }








  
  public Collection retrieve(SuperVO vo, boolean isAnd) throws DAOException {
    PersistenceManager manager = null;
    Collection values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      values = manager.retrieve(vo, isAnd);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    
    return values;
  }


  
  public Collection retrieveOrderBy(SuperVO vo, boolean isAnd, String[] orderbyFields) throws DAOException { return retrieve(vo, isAnd, null, orderbyFields); }


  
  public Collection retrieve(SuperVO vo, boolean isAnd, String[] fields, String[] orderbyFields) throws DAOException {
    PersistenceManager manager = null;
    Collection values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      values = manager.retrieve(vo, isAnd, fields, orderbyFields);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return values;
  }








  
  public Collection retrieve(SuperVO vo, boolean isAnd, String[] fields) throws DAOException {
    PersistenceManager manager = null;
    Collection values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      values = manager.retrieve(vo, isAnd, fields);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return values;
  }








  
  public Collection retrieveByCorp(Class className, String pkCorp, String[] selectedFields) throws DAOException {
    PersistenceManager manager = null;
    Collection values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      
      values = manager.retrieveByCorp(className, pkCorp, selectedFields);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return values;
  }







  
  public Collection retrieveByCorp(Class className, String pkCorp) throws DAOException {
    PersistenceManager manager = null;
    Collection values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      values = manager.retrieveByCorp(className, pkCorp);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return values;
  }







  
  public Object retrieveByPK(Class className, String pk) throws DAOException {
    PersistenceManager manager = null;
    Object values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      values = manager.retrieveByPK(className, pk);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return values;
  }



  
  public Object retrieveByPK(Class className, String pk, String[] selectedFields) throws DAOException {
    PersistenceManager manager = null;
    Object values = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      values = manager.retrieveByPK(className, pk, selectedFields);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return values;
  }







  
  public String insertVOWithPK(SuperVO vo) throws DAOException {
    PersistenceManager manager = null;
    String pk = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      
      pk = manager.insertWithPK(vo);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return pk;
  }






  
  public String insertVO(SuperVO vo) throws DAOException {
    PersistenceManager manager = null;
    String pk = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      
      pk = manager.insert(vo);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return pk;
  }








  
  public String[] insertVOArrayWithPK(SuperVO[] vo) throws DAOException {
    PersistenceManager manager = null;
    String[] pk = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      
      pk = manager.insertWithPK(vo);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return pk;
  }





  
  public String[] insertVOArray(SuperVO[] vo) throws DAOException {
    PersistenceManager manager = null;
    String[] pk = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      
      pk = manager.insert(vo);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return pk;
  }





  
  public String[] insertVOList(List vos) throws DAOException {
    PersistenceManager manager = null;
    String[] pk = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      
      pk = manager.insert(vos);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
    return pk;
  }









  
  public String insertObjectWithPK(Object vo, IMappingMeta meta) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      
      return manager.insertObjectWithPK(vo, meta);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }







  
  public String insertObject(Object vo, IMappingMeta meta) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      
      return manager.insertObject(vo, meta);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    }
  }








  
  public String[] insertObjectWithPK(Object[] vo, IMappingMeta meta) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      String[] res = manager.insertObjectWithPK(vo, meta);
      return res;
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    }
    finally {
    	
      if (manager != null) {
        manager.release();
      }
    	
    } 
  }









  
  public String[] insertObject(Object[] vo, IMappingMeta meta) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.insertObject(vo, meta);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }






  
  public int updateVO(SuperVO vo) throws DAOException { return updateVOArray(new SuperVO[] { vo }); }









  
  public void updateVO(SuperVO vo, String[] fieldNames) throws DAOException { updateVOArray(new SuperVO[] { vo }, fieldNames); }







  
  public int updateVOArray(SuperVO[] vos) throws DAOException { return updateVOArray(vos, null); }








  
  public int updateVOArray(SuperVO[] vos, String[] fieldNames) throws DAOException { return updateVOArray(vos, fieldNames, null, null); }







  
  public void updateVOList(List vos) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.update(vos);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }








  
  public int updateObject(Object vo, IMappingMeta meta) throws DAOException { return updateObject(vo, meta, null); }


  
  public int updateObject(Object[] vos, IMappingMeta meta) throws DAOException { return updateObject(vos, meta, null); }







  
  public UpdateResultVO execUpdateByVoState(SuperVO[] vos, String[] selectedFields) throws DAOException {
    ArrayList<SuperVO> listInsert = new ArrayList<SuperVO>();
    ArrayList<SuperVO> listUpdate = new ArrayList<SuperVO>();
    ArrayList<SuperVO> listDelete = new ArrayList<SuperVO>();
    for (int i = 0; i < vos.length; i++) {
      int status = vos[i].getStatus();
      if (status == 2) {
        listInsert.add(vos[i]);
      } else if (status == 1) {
        listUpdate.add(vos[i]);
      } else if (status == 3) {
        listDelete.add(vos[i]);
      } 
    } 
    UpdateResultVO rsVO = new UpdateResultVO();
    if (listInsert.size() > 0) {
      rsVO.setPks(insertVOArray((SuperVO[])listInsert.toArray(new SuperVO[listInsert.size()])));
    }
    
    if (listUpdate.size() > 0) {
      updateVOArray((SuperVO[])listUpdate.toArray(new SuperVO[listUpdate.size()]), selectedFields);
    }
    if (listDelete.size() > 0) {
      deleteVOArray((SuperVO[])listDelete.toArray(new SuperVO[listDelete.size()]));
    }
    return rsVO;
  }







  
  public UpdateResultVO execUpdateByVoState(SuperVO[] vos) throws DAOException { return execUpdateByVoState(vos, null); }







  
  public void deleteVO(SuperVO vo) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.delete(vo);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }







  
  public void deleteVOArray(SuperVO[] vos) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.delete(vos);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }








  
  public void deleteByPKs(Class className, String[] pks) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.deleteByPKs(className, pks);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }








  
  public void deleteByClause(Class className, String wherestr) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.deleteByClause(className, wherestr);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }

  
  public void deleteByClause(Class className, String wherestr, SQLParameter params) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.deleteByClause(className, wherestr, params);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }








  
  public void deleteByPK(Class className, String pk) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.deleteByPK(className, pk);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }







  
  public void deleteVOList(List vos) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.delete(vos);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }








  
  public void deleteObject(Object vo, IMappingMeta meta) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.deleteObject(vo, meta);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }






  
  public void deleteObject(Object[] vos, IMappingMeta meta) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.deleteObject(vos, meta);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }









  
  public void deleteObject(Object[] vos, IMappingMeta meta, boolean dealNull) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      manager.deleteObject(vos, meta, dealNull);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }








  
  public Collection retrieve(Object vo, IMappingMeta meta) throws DAOException {
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.retrieve(vo, meta);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }








  
  public Collection retrieveAll(Class className, IMappingMeta meta) throws DAOException {
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.retrieveAll(className, meta);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }









  
  public Collection retrieveByClause(Class className, IMappingMeta meta, String condition) throws DAOException {
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.retrieveByClause(className, meta, condition);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }



  
  public Collection retrieveByClause(Class className, IMappingMeta meta, String condition, SQLParameter params) throws DAOException { return retrieveByClause(className, meta, condition, (String[])null, params); }


  
  public Collection retrieveByClause(Class className, IMappingMeta meta, String condition, String[] fields, SQLParameter params) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.retrieveByClause(className, meta, condition, fields, params);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }










  
  public Collection retrieveByClause(Class className, IMappingMeta meta, String condition, String[] fields) throws DAOException {
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.retrieveByClause(className, meta, condition, fields);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }










  
  public int deleteByClause(IMappingMeta meta, String wherestr) throws DAOException { return deleteByClause(meta, wherestr, null); }

  
  public int deleteByClause(IMappingMeta meta, String wherestr, SQLParameter params) throws DAOException {
    PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.deleteByClause(meta, wherestr, params);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }








  
  public int deleteByPK(IMappingMeta meta, String pk) throws DAOException {
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.deleteByPK(meta, pk);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }












  
  public Collection retrieveByCorp(Class c, IMappingMeta meta, String pkCorp, String[] selectedFields) throws DAOException {
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.retrieveByCorp(c, meta, pkCorp, selectedFields);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }










  
  public Collection retrieveByCorp(Class c, IMappingMeta meta, String pkCorp) throws DAOException {
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.retrieveByCorp(c, meta, pkCorp);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }











  
  public Object retrieveByPK(Class className, IMappingMeta meta, String pk, String[] selectedFields) throws DAOException {
    PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.retrieveByPK(className, meta, pk, selectedFields);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }









  
  public Object retrieveByPK(Class className, IMappingMeta meta, String pk) throws DAOException {
	  PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.retrieveByPK(className, meta, pk);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }









  
  public int updateObject(Object vo, IMappingMeta meta, String whereClause) throws DAOException {
	  PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.updateObject(vo, meta, whereClause);
    } catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }











  
  public int updateObject(Object[] vos, IMappingMeta meta, String whereClause) throws DAOException { return updateObject(vos, meta, whereClause, null); }











  
  public int updateObject(Object[] vos, IMappingMeta meta, String whereClause, SQLParameter param) throws DAOException {
	  PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.updateObject(vos, meta, whereClause, param);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }







  
  public int getDBType() { return DataSourceCenter.getInstance().getDatabaseType(this.dataSource); }










  
  protected String getTableName(int dbType, String tableName) {
    String strTn = tableName;
    switch (dbType) {
      case 7:
      case 9:
      case 14:
      case 15:
      case 16:
        strTn = tableName.toLowerCase();
        break;
      
      case 0:
      case 1:
      case 6:
      case 10:
      case 11:
      case 12:
      case 13:
        strTn = tableName.toUpperCase();
        break;
    } 


    
    return strTn;
  }

  
  public boolean isViewExisted(String viewName) throws DAOException {
    if (viewName == null) {
      throw new NullPointerException("viewName is null!");
    }
    boolean isExit = true;
    try {
      int dbType = getDBType();
      if (dbType == 7 || dbType == 15 || dbType == 11 || dbType == 14 || dbType == 16) {
        
        String sql = "select viewname from pg_views where viewname= '" + viewName.toLowerCase() + "'";
        isExit = ((Boolean)executeQuery(sql, new ResultSetProcessor()
            {
              public Object handleResultSet(ResultSet rs) throws SQLException {
                if (rs != null && rs.next()) {
                  return Boolean.valueOf(true);
                }
                return Boolean.valueOf(false);
              }
            })).booleanValue();
      } else {
        
        String sql = "select 1 from " + viewName;
        executeQuery(sql, new ColumnProcessor());
      } 
    } catch (Exception e) {
      Logger.error("BaseDAO isViewExisted EXP", e);
      isExit = false;
    } 
    
    return isExit;
  }








  
  public boolean isTableExisted(String tableName) throws DAOException {
    if (tableName == null) {
      throw new NullPointerException("TableName is null!");
    }
    PersistenceManager manager = null;
    ResultSet rs = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      int dbType = manager.getDBType();
      Logger.debug("baseDao isTableExisted(),dbType:" + dbType);
      DatabaseMetaData dbmd = manager.getMetaData();
      if (dbType == 6 || dbType == 0 || dbType == 7 || dbType == 15 || dbType == 9 || dbType == 8 || dbType == 10 || dbType == 11 || dbType == 13 || dbType == 14 || dbType == 16)
      
      { 
        
        rs = dbmd.getTables(manager.getCatalog(), manager.getSchema(), getTableName(dbType, tableName), new String[] { "TABLE" });
        
        Logger.debug(dbType + " is Table Existed:" + manager.getSchema() + " , tableName" + 
            getTableName(dbType, tableName)); }
      else { if (dbType == 1) {
          rs = dbmd.getTables(manager.getCatalog(), manager.getSchema(), getTableName(dbType, tableName), new String[] { "TABLE" });
          
          while (rs.next()) {
            if (manager.getSchema().equalsIgnoreCase(rs.getString("TABLE_SCHEM")) && tableName.equalsIgnoreCase(rs.getString("TABLE_NAME"))) {
              return true;
            }
          } 
          Logger.debug(dbType + " is Table Existed:" + manager.getSchema() + " , tableName" + 
              getTableName(dbType, tableName));
          return false;
        } 
        if (dbType == 12) {
          Logger.debug("mysql is Table Existed:" + manager.getSchema() + " , tableName" + 
              getTableName(dbType, tableName));
          JdbcSession session = manager.getJdbcSession();
          Connection conn = null;
          Statement stmtStatement = null;
          boolean ret = true;
          try {
            conn = session.getConnection();
            stmtStatement = conn.createStatement();
            stmtStatement.executeQuery("select 1 from " + tableName);
            return ret;
          } catch (Exception e) {
            ret = false;
          } finally {
            try {
              if (stmtStatement != null) {
                stmtStatement.close();
              }
              if (conn != null) {
                conn.close();
              }
              if (manager != null) {
                manager.release();
              }
            } catch (Exception e) {
              Logger.error(e);
            } 
            Logger.debug("Base table:" + tableName + ", is exists:" + ret);
          } 
          return ret;
        } 
        Logger.debug(dbType + " is Table Existed:" + manager.getSchema() + " , tableName" + 
            getTableName(dbType, tableName));
        rs = dbmd.getTables(null, null, getTableName(dbType, tableName), new String[] { "TABLE" }); }
      
      if (rs.next()) {
        Logger.debug("BaseDao table:" + tableName + ", exists!");
        return true;
      } 
      Logger.debug("BaseDao table:" + tableName + ", not exists!");
      return false;
    } catch (Exception e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      DBUtil.closeRs(rs);
      if (manager != null) {
        manager.release();
      }
    } 
  }

  
  public int getMaxRows() { return this.maxRows; }


  
  public void setMaxRows(int maxRows) { this.maxRows = maxRows; }









  
  public int deleteByPKs(IMappingMeta meta, String[] pks) throws DAOException {
	  PersistenceManager manager = null;
    
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.deleteByPKs(meta, pks);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }


  
  public void setAddTimeStamp(boolean addTimeStamp) { this.addTimestamp = addTimeStamp; }


  
  public boolean getAddTimeStamp() { return this.addTimestamp; }


  
  public boolean isSqlTranslate() { return this.sqlTranslate; }


  
  public void setSqlTranslate(boolean sqlTranslate) { this.sqlTranslate = sqlTranslate; }

  
  private PersistenceManager createPersistenceManager(String ds) throws DbException {
    PersistenceManager manager = PersistenceManager.getInstance(ds);
    manager.setMaxRows(this.maxRows);
    manager.setAddTimeStamp(this.addTimestamp);
    return manager;
  }

  
  public int updateVOArray(SuperVO[] vos, String[] fieldNames, String whereClause, SQLParameter param) throws DAOException {
	  PersistenceManager manager = null;
    try {
      manager = createPersistenceManager(this.dataSource);
      return manager.update(vos, fieldNames, whereClause, param);
    }
    catch (DbException e) {
      Logger.error(e.getMessage(), e);
      throw new DAOException(e.getMessage());
    } finally {
      if (manager != null) {
        manager.release();
      }
    } 
  }







  
  public boolean isColumnExisted(String tableName, String columnName) throws DbException {
    List<String> columns = getColumnNames(tableName);
    if (columns != null && !columns.isEmpty()) {
      for (String col : columns) {
        if (col.equalsIgnoreCase(columnName)) {
          return true;
        }
      } 
    }
    return false;
  }







  
  private List<String> getColumnNames(String table) throws DbException {
    table = UAPESAPI.sqlEncode(table);
    ColCache cache = getColCache();
    List<String> result = (List)cache.nameCache.get(table);
    if (result == null || result.size() == 0) {
      List<String> colNames = new ArrayList<String>();
      JdbcSession session = null;
      ResultSet rsColumns = null;
      try {
        if (getDBType() == 2 && table.startsWith("#")) {
        	Connection conn = null;
            PreparedStatement stmt = null;
          try {
            session = new JdbcSession();
            if (session != null) {
              conn = session.getConnection();
              stmt = conn.prepareStatement("select top 0 * from ?");
              stmt.setString(1, table);
              rsColumns = stmt.executeQuery();
              ResultSetMetaData rsMeta = rsColumns.getMetaData();
              int count = rsMeta.getColumnCount();
              for (int i = 1; i < count + 1; i++) {
                colNames.add(rsMeta.getColumnName(i));
              }
              if (colNames.size() > 0) {
                cache.nameCache.put(table, colNames);
              } else {
                throw new UnKnownException("no column info for: " + table);
              } 
              
              return colNames;
            } 
          } finally {
            if (stmt != null) {
              stmt.close();
            }
            if (conn != null) {
              conn.close();
            }
          } 
        } else {
          session = new JdbcSession();
          if (session != null) {
            DatabaseMetaData metaData = session.getMetaData();
            if (getDBType() == 2) {
              rsColumns = metaData.getColumns(null, null, table.toUpperCase(), "%");
            } else if (getDBType() == 7 || getDBType() == 16) {
              rsColumns = metaData.getColumns(null, null, table.toLowerCase(), "%");
            } else if (getDBType() == 15) {
              rsColumns = metaData.getColumns(null, null, table.toLowerCase(), "%");
            } else if (getDBType() == 9 || getDBType() == 13) {
              rsColumns = metaData.getColumns(null, null, table.toLowerCase(), "%");
            } else if (getDBType() == 12) {
              rsColumns = metaData.getColumns(null, null, table.toLowerCase(), "%");
            } else {
              rsColumns = metaData.getColumns(null, getSchema(metaData), table.toUpperCase(), "%");
            } 
            while (rsColumns.next()) {
              String columnName = rsColumns.getString("COLUMN_NAME").toUpperCase();
              colNames.add(columnName);
            } 
            return colNames;
          } 
        } 
      } catch (SQLException e) {
        Logger.error("get table metadata error", e);
        throw ExceptionFactory.getException(getDBType(), "get table metadata error", e);
      } finally {
        DBUtil.closeRs(rsColumns);
        if (session != null) {
          session.closeAll();
        }
      } 
    } 
    
    return result;
  }
  private String getSchema(DatabaseMetaData metaData) {
    String strSche = null;
    try {
      String schema = metaData.getUserName();
      switch (getDBType()) {
        case 7:
        case 9:
        case 14:
        case 15:
        case 16:
          strSche = null;
          break;
        case 2:
          strSche = "dbo";
          break;
        case 0:
        case 1:
        case 6:
        case 10:
        case 11:
        case 12:
        case 13:
          if (schema == null || schema.length() == 0) {
            throw new IllegalArgumentException("ORACLE Database mode does not allow to be null!!");
          }
          
          strSche = schema.toUpperCase();
          break;
      } 


    
    } catch (Exception e) {
      Logger.error(e.getMessage(), e);
    } 
    return strSche;
  }
}